/**
 * 短信读取服务（仅Android平台）
 * 提供短信读取、监听和快递信息识别功能
 */

import ExpressCompanyDetector from './express-company-detector.js';

class SMSReaderService {
  static isListening = false;
  static receiver = null;

  /**
   * 检查短信读取权限
   * @returns {Promise<boolean>} 是否有权限
   */
  static async checkPermission() {
    // #ifdef APP-PLUS
    if (typeof plus === 'undefined' || plus.os.name !== 'Android') {
      return false;
    }

    return new Promise((resolve) => {
      plus.android.requestPermissions(
        ['android.permission.READ_SMS'],
        (result) => {
          const granted = result.granted && result.granted.length > 0;
          resolve(granted);
        },
        (error) => {
          console.error('检查短信权限失败:', error);
          resolve(false);
        }
      );
    });
    // #endif

    // #ifndef APP-PLUS
    return false;
    // #endif
  }

  /**
   * 请求短信读取权限
   * @returns {Promise<boolean>} 是否授权成功
   */
  static async requestPermission() {
    // #ifdef APP-PLUS
    if (typeof plus === 'undefined' || plus.os.name !== 'Android') {
      return false;
    }

    return new Promise((resolve) => {
      plus.android.requestPermissions(
        ['android.permission.READ_SMS', 'android.permission.RECEIVE_SMS'],
        (result) => {
          const granted = result.granted && result.granted.length > 0;
          resolve(granted);
        },
        (error) => {
          console.error('请求短信权限失败:', error);
          resolve(false);
        }
      );
    });
    // #endif

    // #ifndef APP-PLUS
    return false;
    // #endif
  }

  /**
   * 读取短信内容
   * @param {number} limit - 读取数量限制，默认50条
   * @returns {Promise<Array>} 短信列表
   */
  static async readSMS(limit = 50) {
    // #ifdef APP-PLUS
    if (typeof plus === 'undefined' || plus.os.name !== 'Android') {
      throw new Error('仅支持Android平台');
    }

    try {
      const main = plus.android.runtimeMainActivity();
      const Uri = plus.android.importClass('android.net.Uri');
      const ContentResolver = main.getContentResolver();

      // 查询短信数据库
      const uri = Uri.parse('content://sms/inbox');
      const projection = ['_id', 'address', 'body', 'date', 'read'];
      const cursor = ContentResolver.query(
        uri,
        projection,
        null,
        null,
        'date DESC'
      );

      const messages = [];
      let count = 0;

      if (cursor && cursor.moveToFirst()) {
        do {
          if (count >= limit) break;

          const id = cursor.getString(0);
          const address = cursor.getString(1);
          const body = cursor.getString(2);
          const date = cursor.getLong(3);
          const read = cursor.getInt(4);

          messages.push({
            id,
            address,
            body,
            date,
            read: read === 1,
            timestamp: new Date(date)
          });

          count++;
        } while (cursor.moveToNext());
      }

      if (cursor) {
        cursor.close();
      }

      return messages;
    } catch (error) {
      console.error('读取短信失败:', error);
      throw error;
    }
    // #endif

    // #ifndef APP-PLUS
    throw new Error('仅支持Android平台');
    // #endif
  }

  /**
   * 从短信中识别快递信息
   * @param {Array} messages - 短信列表
   * @returns {Array} 快递信息列表
   */
  static extractExpressInfoFromSMS(messages) {
    const expressInfoList = [];

    for (const message of messages) {
      const info = ExpressCompanyDetector.extractExpressInfo(message.body);
      if (info) {
        expressInfoList.push({
          ...info,
          smsId: message.id,
          smsAddress: message.address,
          smsBody: message.body,
          smsDate: message.date,
          smsTimestamp: message.timestamp
        });
      }
    }

    return expressInfoList;
  }

  /**
   * 扫描短信并识别快递信息
   * @param {number} limit - 扫描数量限制
   * @returns {Promise<Array>} 快递信息列表
   */
  static async scanSMSForExpress(limit = 50) {
    try {
      const messages = await this.readSMS(limit);
      return this.extractExpressInfoFromSMS(messages);
    } catch (error) {
      console.error('扫描短信失败:', error);
      throw error;
    }
  }

  /**
   * 启动短信监听（实时监听新短信）
   * @param {Function} callback - 收到新短信时的回调函数
   * @returns {boolean} 是否启动成功
   */
  static startSMSListener(callback) {
    // #ifdef APP-PLUS
    if (typeof plus === 'undefined' || plus.os.name !== 'Android') {
      console.warn('仅支持Android平台');
      return false;
    }

    if (this.isListening) {
      console.warn('短信监听已启动');
      return true;
    }

    try {
      const main = plus.android.runtimeMainActivity();
      const IntentFilter = plus.android.importClass('android.content.IntentFilter');
      const BroadcastReceiver = plus.android.importClass('android.content.BroadcastReceiver');
      const SmsMessage = plus.android.importClass('android.telephony.SmsMessage');

      // 创建广播接收器
      this.receiver = plus.android.implements('android.content.BroadcastReceiver', {
        onReceive: function(context, intent) {
          try {
            const bundle = intent.getExtras();
            if (!bundle) return;

            const pdus = bundle.get('pdus');
            if (!pdus) return;

            const format = bundle.getString('format');

            for (let i = 0; i < pdus.length; i++) {
              let message;
              if (format) {
                message = SmsMessage.createFromPdu(pdus[i], format);
              } else {
                message = SmsMessage.createFromPdu(pdus[i]);
              }

              const body = message.getMessageBody();
              const sender = message.getOriginatingAddress();
              const timestamp = message.getTimestampMillis();

              // 识别快递信息
              const expressInfo = ExpressCompanyDetector.extractExpressInfo(body);
              
              if (expressInfo && callback) {
                callback({
                  ...expressInfo,
                  smsAddress: sender,
                  smsBody: body,
                  smsDate: timestamp,
                  smsTimestamp: new Date(timestamp)
                });
              }
            }
          } catch (error) {
            console.error('处理短信广播失败:', error);
          }
        }
      });

      // 注册广播接收器
      const filter = new IntentFilter('android.provider.Telephony.SMS_RECEIVED');
      main.registerReceiver(this.receiver, filter);

      this.isListening = true;
      console.log('短信监听已启动');
      return true;
    } catch (error) {
      console.error('启动短信监听失败:', error);
      return false;
    }
    // #endif

    // #ifndef APP-PLUS
    console.warn('仅支持Android平台');
    return false;
    // #endif
  }

  /**
   * 停止短信监听
   * @returns {boolean} 是否停止成功
   */
  static stopSMSListener() {
    // #ifdef APP-PLUS
    if (typeof plus === 'undefined' || plus.os.name !== 'Android') {
      return false;
    }

    if (!this.isListening || !this.receiver) {
      console.warn('短信监听未启动');
      return false;
    }

    try {
      const main = plus.android.runtimeMainActivity();
      main.unregisterReceiver(this.receiver);
      
      this.receiver = null;
      this.isListening = false;
      
      console.log('短信监听已停止');
      return true;
    } catch (error) {
      console.error('停止短信监听失败:', error);
      return false;
    }
    // #endif

    // #ifndef APP-PLUS
    return false;
    // #endif
  }

  /**
   * 检查是否正在监听
   * @returns {boolean}
   */
  static isListeningActive() {
    return this.isListening;
  }
}

export default SMSReaderService;
